// ESM
import { createCanvas, registerFont } from 'canvas';
import fs from 'fs';
import {width,height}from'./config'
// 模拟抗锯齿
function testAntialias(ctx, width, height) {

// 获取像素数据
    const imgData = ctx.getImageData(0, 0, width, height);
    const data = imgData.data;

// 二值化阈值
    for (let i = 0; i < data.length; i += 4) {
        // data[i] = R, data[i+1] = G, data[i+2] = B
        // data[i+3] = A
        const gray = 0.299 * data[i] + 0.587 * data[i+1] + 0.114 * data[i+2];
        if (gray < 128) {
            data[i] = data[i+1] = data[i+2] = 0; // 黑
            data[i+3] = 255;
        } else {
            data[i] = data[i+1] = data[i+2] = 255; // 白
            data[i+3] = 255;
        }
    }

    ctx.putImageData(imgData, 0, 0);
}

export function nodeCanvasTest(){
    console.time('nodeCanvasTest');

// 注册本地字体（中文示例）
    registerFont('./font/ddjinbu.ttf', { family: 'ddjinbu' });

    const canvas = createCanvas(width, height);
    const ctx = canvas.getContext('2d');

// 背景
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, width, height);

// 文字样式（引用注册的字体）
    ctx.fillStyle = '#000';
    ctx.font = '20px ddjinbu';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    // ctx.imageSmoothingEnabled = false;
    // ctx.patternQuality="fast"
    // ctx.antialias="none"
    ctx.fillText('你好钉钉进步体!', width / 2, height / 2);


    // testAntialias(ctx, width, height)




    const buffer = canvas.toBuffer('image/png');
    fs.writeFileSync('./image/node-canvas-test.png', buffer);
    console.log('saved text.png');
    console.timeEnd('nodeCanvasTest');
    return Promise.resolve('./image/node-canvas-test.png');

}
